package com.aurora.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.aurora.common.utils.R;
import com.aurora.common.vo.MemberResponseVo;
import com.aurora.gulimall.order.feign.CartFeignService;
import com.aurora.gulimall.order.feign.MemberFeignService;
import com.aurora.gulimall.order.feign.WareFeignService;
import com.aurora.gulimall.order.interceptor.LoginUserInterceptor;
import com.aurora.gulimall.order.vo.MemberAddressVo;
import com.aurora.gulimall.order.vo.OrderConfirmVo;
import com.aurora.gulimall.order.vo.OrderItemVo;
import com.aurora.gulimall.order.vo.SkuHasStockVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aurora.common.utils.PageUtils;
import com.aurora.common.utils.Query;

import com.aurora.gulimall.order.dao.OrderDao;
import com.aurora.gulimall.order.entity.OrderEntity;
import com.aurora.gulimall.order.service.OrderService;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WareFeignService wareFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**订单确认页
     * @return
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
//        System.out.println("主线程。。。"+Thread.currentThread().getId());
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //1、远程查询收货地址列表
        CompletableFuture<Void> addrTask = CompletableFuture.runAsync(() -> {
//            System.out.println("addr线程。。。"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResponseVo.getId());
            confirmVo.setAddress(address);
        }, executor);
        //2、远程查询购物车选中项
        CompletableFuture<Void> itemTask = CompletableFuture.runAsync(() -> {
//            System.out.println("item线程。。。"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(currentUserCartItems);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIds = items.stream().map(item -> {
                return item.getSkuId();
            }).collect(Collectors.toList());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            List<SkuHasStockVo> data = skuHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            });
            if(data != null){
                Map<Long, Boolean> map = data.stream()
                        .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        },executor);
        //3、查询用户积分
        Integer integration = memberResponseVo.getIntegration();
        confirmVo.setIntegration(integration);
        //4、其他数据自动计算
        CompletableFuture.allOf(addrTask,itemTask).get();
        return confirmVo;
    }

}